package com.tangding.interceptors;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.tangding.common.tools.ErrorConstants;
import com.tangding.common.utils.JacksonUtil;
import com.tangding.pojo.response.MessageDto;

public abstract class BaseInterceptor implements HandlerInterceptor {
	
	/**
	 * 返回错误消息
	 * 
	 * @param response
	 * @param errorCode
	 * @param msg
	 * @param data
	 * @throws IOException
	 */
	protected void sendErrorMsgView(HttpServletResponse response, int errorCode, String msg, String redirect) throws IOException {
		ModelAndView dto = new ModelAndView();
		dto.setViewName(redirect);
		dto.addObject("msg", msg);
		dto.addObject("code", errorCode);
		String result = JacksonUtil.toJson(dto);
		response.setHeader("Content-Type", "application/json; charset=UTF-8");
		PrintWriter writer = response.getWriter();
		writer.write(result);
		writer.flush();
	}
	
	protected void sendErrorMsgView(HttpServletResponse response, int errorCode, String redirect) throws IOException {
		sendErrorMsgView(response, errorCode, ErrorConstants.getDesc(errorCode), redirect);
	}
	
	/**
	 * 返回错误消息
	 * 
	 * @param response
	 * @param errorCode
	 * @param msg
	 * @param data
	 * @throws IOException
	 */
	protected void sendErrorMsg(HttpServletResponse response, int errorCode, String msg, Object data) throws IOException {
		MessageDto dto = new MessageDto();
		dto.setCode(errorCode);
		dto.setMsg(msg);
		dto.setData(data);
		String result = JacksonUtil.toJson(dto);
		response.setHeader("Content-Type", "application/json; charset=UTF-8");
		PrintWriter writer = response.getWriter();
		writer.write(result);
		writer.flush();
	}
	
	/**
	 * 返回错误消息
	 * 
	 * @param response
	 * @param errorCode
	 * @param msg
	 * @throws IOException
	 */
	protected void sendErrorMsg(HttpServletResponse response, int errorCode, String msg) throws IOException {
		sendErrorMsg(response, errorCode, msg, null);
	}
	
	/**
	 * 返回错误消息
	 * 
	 * @param response
	 * @param errorCode
	 * @param msg
	 * @throws IOException
	 */
	protected void sendErrorMsgByCode(HttpServletResponse response, int errorCode) throws IOException {
		sendErrorMsg(response, errorCode, ErrorConstants.getDesc(errorCode), null);
	}
	
	/**
	 * 返回错误消息
	 * 
	 * @param response
	 * @param errorCode
	 * @param msg
	 * @throws IOException
	 */
	protected void sendErrorMsgByCode(HttpServletResponse response, int errorCode, Object data) throws IOException {
		sendErrorMsg(response, errorCode, ErrorConstants.getDesc(errorCode), data);
	}
}